//
//  weatherViewController.m
//  Focus
//
//  Created by 楼主 on 14-10-27.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "weatherViewController.h"
#import "BATableView.h"
#import "Weather.h"
#import "subscribeController.h"
#import "SearchBarViewController.h"
#import "WeiPlist.h"
#import "NetHandler.h"
#import "WeatherTableViewCell.h"
@interface weatherViewController ()<BATableViewDelegate,UISearchBarDelegate,CLLocationManagerDelegate, MKMapViewDelegate>
@property (nonatomic, strong) BATableView *contactTableView;
@property (nonatomic, strong) NSArray * dataSource;
@property (nonatomic, retain) AIMTableViewIndexBar *indexBar;
@property (nonatomic, retain) UITableView *plainTableView;
@property (nonatomic, retain) NSArray *sections;
@property (nonatomic, retain) NSArray *rows;
@property (nonatomic, retain) Weather *weather;
@property (nonatomic, retain) NSMutableArray *showArray;
@property (nonatomic, retain) NSMutableArray *array;

@property(nonatomic , retain)CLLocationManager *LocationManager;
@property(nonatomic , assign)CLLocationCoordinate2D mylocation;

@property (nonatomic, retain) UIButton *buttonGPS;
@property (nonatomic, retain) NSDictionary *mapDic;//  用来存储定位后获得的信息（国家，城市，市区，街道等）

@property (nonatomic, retain)UILabel *dingLabel;
@end

@implementation weatherViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        NSNotificationCenter *notiCenter1 = [NSNotificationCenter defaultCenter];
        [notiCenter1 addObserver:self selector:@selector(recetiveNotification:) name:@"weatherChange1" object:nil];
    }
    return self;
}
- (void)dealloc
{
    [super dealloc];
    [_contactTableView release];
    [_dataSource release];
    [_indexBar release];
    [_plainTableView release];
    [_sections release];
    [_rows release];
    [_weather release];
    [_showArray release];
    [_array release];
    [_resultArray release];
}

- (void)recetiveNotification:(NSNotification *)noti
{
    SearchBarViewController *searchVC = [[SearchBarViewController alloc]init];
    
    searchVC.searchArray = noti.object;
    
    [self.navigationController pushViewController:searchVC animated:YES];
    [searchVC release];
}


#pragma mark 刷新页面
- (void)viewDidAppear:(BOOL)animated
{
    [self.contactTableView reloadData];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.translucent = NO;
    self.title = @"请选择你所在的城市";
#pragma mark 从沙盒中解析城市数据
    
    self.array = [NSMutableArray array];
    self.showArray = [NSMutableArray array];
    UISearchBar *searchBar = [[UISearchBar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
    searchBar.placeholder=@"请输入您要查询的城市";
    searchBar.delegate = self;
    searchBar.barStyle = UIBarStyleDefault;
    searchBar.showsCancelButton = YES;
    searchBar.autocorrectionType = UITextAutocorrectionTypeDefault;
    searchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
    
    [self.view addSubview:searchBar];
    

    
    self.dingLabel = [[UILabel alloc]initWithFrame:CGRectMake(130, 50, 100, 50)];
    
    [self.view addSubview:self.dingLabel];
    
    UIButton *dingButton = [UIButton buttonWithType:UIButtonTypeSystem];
    
    dingButton.frame = CGRectMake(50, 50, 100, 50);
    
    [dingButton setTitle:@"点击定位" forState:UIControlStateNormal];
    
    [dingButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:dingButton];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"首页" style:UIBarButtonItemStyleBordered target:self action:@selector(barAction:)];
#pragma mark 创建section 数组
    NSMutableArray *arrA = [NSMutableArray array];
    NSMutableArray *arrB = [NSMutableArray array];
    NSMutableArray *arrC = [NSMutableArray array];
    NSMutableArray *arrD = [NSMutableArray array];
    NSMutableArray *arrE = [NSMutableArray array];
    NSMutableArray *arrF = [NSMutableArray array];
    NSMutableArray *arrG = [NSMutableArray array];
    NSMutableArray *arrH = [NSMutableArray array];
    NSMutableArray *arrJ = [NSMutableArray array];
    NSMutableArray *arrK = [NSMutableArray array];
    NSMutableArray *arrL = [NSMutableArray array];
    NSMutableArray *arrM = [NSMutableArray array];
    NSMutableArray *arrN = [NSMutableArray array];
    NSMutableArray *arrP = [NSMutableArray array];
    NSMutableArray *arrQ = [NSMutableArray array];
    NSMutableArray *arrR = [NSMutableArray array];
    NSMutableArray *arrS = [NSMutableArray array];
    NSMutableArray *arrT = [NSMutableArray array];
    NSMutableArray *arrW = [NSMutableArray array];
    NSMutableArray *arrX = [NSMutableArray array];
    NSMutableArray *arrY = [NSMutableArray array];
    NSMutableArray *arrZ = [NSMutableArray array];
    
#pragma mark 解析城市名
    WeiPlist *wei = [[WeiPlist alloc]init];
    NSDictionary *dic =  [wei dictionaryData:@"weather_cities"];
    NSArray *arr1 = [dic objectForKey:@"cities"];
    
    for (NSDictionary *dicCity in arr1) {
        NSString *str = [dicCity objectForKey:@"letter"];
        if ([str hasPrefix:@"a"]) {
            [arrA addObject:[dicCity objectForKey:@"name"]];
        } else if ([str hasPrefix:@"b"]) {
            [arrB addObject:[dicCity objectForKey:@"name"]];
        } else if ([str hasPrefix:@"c"]) {
            [arrC addObject:[dicCity objectForKey:@"name"]];
        } else if ([str hasPrefix:@"d"]) {
            [arrD addObject:[dicCity objectForKey:@"name"]];
        } else if ([str hasPrefix:@"e"]) {
            [arrE addObject:[dicCity objectForKey:@"name"]];
        } else if ([str hasPrefix:@"f"]) {
            [arrF addObject:[dicCity objectForKey:@"name"]];
        } else if ([str hasPrefix:@"g"]) {
            [arrG addObject:[dicCity objectForKey:@"name"]];
        } else if ([str hasPrefix:@"h"]) {
            [arrH addObject:[dicCity objectForKey:@"name"]];
        } else if ([str hasPrefix:@"j"]) {
            [arrJ addObject:[dicCity objectForKey:@"name"]];
        } else if ([str hasPrefix:@"k"]) {
            [arrK addObject:[dicCity objectForKey:@"name"]];
        } else if ([str hasPrefix:@"l"]) {
            [arrL addObject:[dicCity objectForKey:@"name"]];
        } else if ([str hasPrefix:@"m"]) {
            [arrM addObject:[dicCity objectForKey:@"name"]];
        } else if ([str hasPrefix:@"n"]) {
            [arrN addObject:[dicCity objectForKey:@"name"]];
        }  else if ([str hasPrefix:@"p"]) {
            [arrP addObject:[dicCity objectForKey:@"name"]];
        } else if ([str hasPrefix:@"q"]) {
            [arrQ addObject:[dicCity objectForKey:@"name"]];
        } else if ([str hasPrefix:@"r"]) {
            [arrR addObject:[dicCity objectForKey:@"name"]];
        } else if ([str hasPrefix:@"s"]) {
            [arrS addObject:[dicCity objectForKey:@"name"]];
        } else if ([str hasPrefix:@"t"]) {
            [arrT addObject:[dicCity objectForKey:@"name"]];
        }  else if ([str hasPrefix:@"w"]) {
            [arrW addObject:[dicCity objectForKey:@"name"]];
        } else if ([str hasPrefix:@"x"]) {
            [arrX addObject:[dicCity objectForKey:@"name"]];
        } else if ([str hasPrefix:@"y"]) {
            [arrY addObject:[dicCity objectForKey:@"name"]];
        } else {
            [arrZ addObject:[dicCity objectForKey:@"name"]];
        }
        [self.array addObject:[dicCity objectForKey:@"name"]];
    }
#pragma mark 热门城市
    
    NSMutableArray *hotCity = [dic objectForKey:@"hot_cities"];
    NSMutableArray *hot = [NSMutableArray array];
    for (NSDictionary *dic2 in hotCity) {
        [hot addObject:[dic2 objectForKey:@"name"]];
    }
    self.dataSource = @[@{@"indexTitle": @"热",@"data":hot},
                        @{@"indexTitle": @"A",@"data":arrA},
                        @{@"indexTitle": @"B",@"data":arrB},
                        @{@"indexTitle": @"C",@"data":arrC},
                        @{@"indexTitle": @"D",@"data":arrD},
                        @{@"indexTitle": @"E",@"data":arrE},
                        @{@"indexTitle": @"F",@"data":arrF},
                        @{@"indexTitle": @"G",@"data":arrG},
                        @{@"indexTitle": @"H",@"data":arrH},
                        @{@"indexTitle": @"J",@"data":arrJ},
                        @{@"indexTitle": @"K",@"data":arrK},
                        @{@"indexTitle": @"L",@"data":arrL},
                        @{@"indexTitle": @"M",@"data":arrM},
                        @{@"indexTitle": @"N",@"data":arrN},
                        @{@"indexTitle": @"P",@"data":arrP},
                        @{@"indexTitle": @"Q",@"data":arrQ},
                        @{@"indexTitle": @"R",@"data":arrR},
                        @{@"indexTitle": @"S",@"data":arrS},
                        @{@"indexTitle": @"T",@"data":arrT},
                        @{@"indexTitle": @"W",@"data":arrW},
                        @{@"indexTitle": @"X",@"data":arrX},
                        @{@"indexTitle": @"Y",@"data":arrY},
                        @{@"indexTitle": @"Z",@"data":arrZ}];
    [self createTableView];
}


#pragma mark 创建tableView
- (void) createTableView {
    
    self.contactTableView = [[BATableView alloc] initWithFrame:CGRectMake(0, 100, 320, 380)];
    self.contactTableView.delegate = self;
    [self.view addSubview:self.contactTableView];
    
    [self.contactTableView release];
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *currentLocation = [locations lastObject];
    self.mylocation = currentLocation.coordinate;
    
    self.geocoder = [[CLGeocoder alloc]init];
    [self.geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *placemarks, NSError *error) {
        
        for (CLPlacemark *placeMark in placemarks) {
            self.mapDic = [placeMark addressDictionary];
    
//            NSLog(@"  Country %@",[self.mapDic objectForKey:@"Country"]);
//            NSLog(@"State  %@", [self.mapDic objectForKey:@"State"]);
//            NSLog(@"City  %@", [self.mapDic objectForKey:@"City"]);
//            NSLog(@"Street %@", [self.mapDic objectForKey:@"Street"]);
//
//            [self.buttonGPS setTitle:[self.mapDic objectForKey:@"City"] forState:UIControlStateNormal];
            NSString *str = @"http://iphone.myzaker.com/zaker/get_weather.php?city=";
            NSString *string = [self.mapDic objectForKey:@"City"];

            self.dingLabel.text = string;
            
            int long length = [string length];
            NSString *string1 = [string substringToIndex:length - 1];
            NSString *cityName = [str stringByAppendingString:string1];
            [NetHandler networkWithURL:cityName comaletion:^(id result) {
                NSDictionary *weather = [[result objectForKey:@"data"]objectForKey:@"datas"];
                
                self.weather = [[Weather alloc] init];
                self.weather.tmax = [weather objectForKey:@"tmax"];
                self.weather.tmin = [weather objectForKey:@"tmin"];
                self.weather.weather_day = [weather objectForKey:@"weather_day"];
//                NSLog(@"%@",self.weather.weather_day);
                
                self.weather.weather_night = [weather objectForKey:@"weather_night"];
                self.weather.title = [self.mapDic objectForKey:@"City"];
                
                
            }];
        }
    }];
    [_geocoder release];
}

-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
        NSLog(@"失败了");
//    [self.buttonGPS setTitle:@"定位失败" forState:UIControlStateNormal];
}

#pragma mark  点击按钮时开始定位
-(void)buttonClicked:(UIButton *)button
{
    if ([CLLocationManager locationServicesEnabled]) {
        self.LocationManager = [[CLLocationManager alloc]init];
        self.LocationManager.delegate = self;
        
        //选择定位的方式为最优的状态.
        self.LocationManager.desiredAccuracy = kCLLocationAccuracyBest;
        
        //触发事件的最小距离
        self.LocationManager.distanceFilter = 1.0f;
        
        [self.LocationManager startUpdatingLocation];
        
    }
}

#pragma mark 创建searchBar
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    NSNotificationCenter *noti = [NSNotificationCenter defaultCenter];
    
    [noti postNotificationName:@"weatherChange1" object:self.array];
}
#pragma mark searchBar的点击事件
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - UITableViewDataSource
- (NSArray *) sectionIndexTitlesForABELTableView:(BATableView *)tableView {
    NSMutableArray * indexTitles = [NSMutableArray array];
    for (NSDictionary * sectionDictionary in self.dataSource) {
        [indexTitles addObject:sectionDictionary[@"indexTitle"]];
    }
    return indexTitles;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return self.dataSource[section][@"indexTitle"];
}

- (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
    return self.dataSource.count;
}

- (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [self.dataSource[section][@"data"] count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString * cellName = @"UITableViewCell";
    
    WeatherTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if (!cell) {
        cell = [[[WeatherTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName]autorelease];
    }
    cell.cityNameLabel.text = self.dataSource[indexPath.section][@"data"][indexPath.row];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *str = @"http://iphone.myzaker.com/zaker/get_weather.php?city=";
    NSString *strWeather = [str stringByAppendingFormat:@"%@",self.dataSource[indexPath.section][@"data"][indexPath.row]];
    [NetHandler networkWithURL:strWeather comaletion:^(id result) {
        NSDictionary *weather = [[result objectForKey:@"data"]objectForKey:@"datas"];
        
        self.weather = [[Weather alloc] init];
        self.weather.tmax = [weather objectForKey:@"tmax"];
        self.weather.tmin = [weather objectForKey:@"tmin"];
        self.weather.weather_day = [weather objectForKey:@"weather_day"];
        NSLog(@"%@",self.weather.weather_day);
        
        self.weather.weather_night = [weather objectForKey:@"weather_night"];
        self.weather.title = self.dataSource[indexPath.section][@"data"][indexPath.row];
        
    }];
    
    NSString * cellName = @"UITableViewCell2";
    
    WeatherTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellName];
    if (!cell) {
        cell = [[[WeatherTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellName]autorelease];
    }
    cell.myImageView.image = [UIImage imageNamed:@"duigou.png"];
    

}
- (void)barAction:(UIBarButtonItem *)bar
{
    NSNotificationCenter *noti = [NSNotificationCenter defaultCenter];
    
    [noti postNotificationName:@"weatherChange" object:self.weather];
    
    [self.navigationController popViewControllerAnimated:YES];
    
// 将天气信息写入本地
    NSUserDefaults *myUser = [NSUserDefaults standardUserDefaults];
    
    [myUser setObject:self.weather.title forKey:@"title"];
    [myUser setObject:self.weather.tmax forKey:@"tmax"];
    [myUser setObject:self.weather.tmin forKey:@"tmin"];
    [myUser setObject:self.weather.weather_day forKey:@"weather_day"];
    [myUser synchronize];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
